package it.polimi.swKnights.SWIMv2.servlets.messages;

import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.ejb.messages.MessageHandlerBeanRemote;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJBException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class SendMessageController
 */
public class SendMessageController extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession session = request.getSession();

		String message = request.getParameter("message");

		String recipient = request.getParameter("recipient");
		List<String> allRecipients = this.getAllRecipients(recipient);

		String object = request.getParameter("object");

		String sender = (String) session.getAttribute("userName");
		String password = (String) session.getAttribute("password");

		if (sender == null)
		{
			sender = "guest";
		}

		MessageHandlerBeanRemote messageBeans = this
				.lookUp(MessageHandlerBeanRemote.class);

		try
		{
			messageBeans.persistMessage(message, allRecipients, sender,
					password, object);
			
			if(session.getAttribute("user_type").equals("guest"))
			{
				response.sendRedirect("./message?message=sendSuccess");
			}
			else
			{
				response.sendRedirect("./messageHome?message=sendSucces");
			}
		}
		catch (EJBException e)
		{
			
			response.sendRedirect("./messageHome?error=" + Errors.notfound);
		}
		catch (LoginFailException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.session);
		}
		catch (InvalidLoginPrivilegesException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.notuser);
		}
		

	}

	private List<String> getAllRecipients(String recipient)
	{
		List<String> recipientList = new ArrayList<String>();
		String[] allRecipients = recipient.split(",");
		for (int i = 0; i < allRecipients.length; i++)
		{
			String correctedString = allRecipients[i].replaceAll(" ", "");
			recipientList.add(correctedString);
		}
		return recipientList;
	}

}
